//
//  KaiSuoSearchViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/18.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "KaiSuoSearchViewController.h"

#import "GXCell.h"
#import "KSDetViewController.h"
@interface KaiSuoSearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>{
    NSMutableArray *array;
    NSMutableArray *datas;//历史记录
    UIView *NoView;
}

@property (nonatomic,copy)NSString *searchStr;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UITableView *tableViewHis;

@end

@implementation KaiSuoSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    [self showNav:@"搜索"];
    array = [NSMutableArray array];
    datas = [NSMutableArray array];
    datas = [user objectForKey:@"myArrayKaiSuo"];
    [self loadUI];
    
}

- (void)loadUI{
    UIView * viewBg = [[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 40)];
    viewBg.backgroundColor = COLOR_RGB(193, 193, 198, 1.0);
    [self.view addSubview:viewBg];

    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 5, ScreenWidth, 30)];
    searchBar.placeholder = @"输入您想搜索的内容";
//    [searchBar setShowsCancelButton:YES animated:YES];
    searchBar.delegate = self;
    [self.view addSubview:searchBar];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 104, ScreenWidth, ScreenHeight-94) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
    
    _tableViewHis = [[UITableView alloc] initWithFrame:CGRectMake(0, 104, ScreenWidth, ScreenHeight-94) style:UITableViewStylePlain];
    _tableViewHis.delegate = self;
    _tableViewHis.dataSource = self;
    _tableViewHis.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableViewHis];
    
    NoView = [[UIView alloc] initWithFrame:CGRectMake(0, 104, ScreenWidth, ScreenHeight-94)];
    NoView.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    NoView.hidden = YES;
    [self.view addSubview:NoView];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 250, 20)];
    lab.text = @"抱歉，没找到您想搜索的内容-_-";
    [NoView addSubview:lab];
    
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"点击搜索框");
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    
    return YES;
}
//点击搜索按钮
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    _searchStr = searchBar.text;
    //读取数组NSArray类型的数据
    NSArray *myArray = [[NSArray alloc] initWithArray:[user arrayForKey:@"myArrayKaiSuo"]];
    
    // NSArray --> NSMutableArray
    NSMutableArray *searTXT = [NSMutableArray array];
    searTXT = [myArray mutableCopy];
    
    BOOL isEqualTo1,isEqualTo2;
    isEqualTo1 = NO,isEqualTo2 = NO;
    
    if (searTXT.count > 0) {
        isEqualTo2 = YES;
        //判断搜索内容是否存在，存在的话放到数组最后一位，不存在的话添加。
        for (NSString * str in myArray) {
            if ([_searchStr isEqualToString:str]) {
                //获取指定对象的索引
                NSUInteger index = [myArray indexOfObject:_searchStr];
                [searTXT removeObjectAtIndex:index];
                [searTXT addObject:_searchStr];
                isEqualTo1 = YES;
                break;
            }
        }
    }
    
    if (!isEqualTo1 || !isEqualTo2) {
        [searTXT addObject:_searchStr];
    }
    
    if(searTXT.count > 15)
    {
        [searTXT removeObjectAtIndex:0];
    }
    //开锁历史
    [user setObject:searTXT forKey:@"myArrayKaiSuo"];
    [self loadData:_searchStr];
    [searchBar resignFirstResponder];
}
//点击取消按钮
-(void)searchBarCancelButtonClicked:(UISearchBar*)searchBar
{
    NSLog(@"searchBarCancelButtonClicked");
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _tableView) {
        return array.count;
    }else{
        return datas.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        static NSString *cellId = @"Cell0";
        GXCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"GXCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = array[indexPath.row];
        cell.labTit.text = [dic objectForKey:@"name"];
        cell.labDet.text = [dic objectForKey:@"profile"];
        NSString *pic = [dic objectForKey:@"figurepic"];
        NSArray *arr = [pic componentsSeparatedByString:@"|"];
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],arr[0]];
        
        [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"TIM截图20170819150938"]];
        
        NSString *km = [NSString stringWithFormat:@" %.2fkm",[[dic objectForKey:@"km"] floatValue]];
        NSString *order = [NSString stringWithFormat:@" %li",[[dic objectForKey:@"order"] integerValue]];
        
        NSString *star = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"star"] integerValue]];
        CGFloat count = [star floatValue];
        StarView *starView = [[StarView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
        starView.showStar = count * 20;
        [cell.starView addSubview:starView];
        
        [cell.btnL setTitle:km forState:UIControlStateNormal];
        [cell.btnC setTitle:order forState:UIControlStateNormal];
        
        return cell;
    }else{
        static NSString *cellId = @"Cell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = datas[indexPath.row];
        
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        return 163.0;
    }
    return 44.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    view.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16, 10, 100, 20)];
    lab.text = @"历史搜索";
    [view addSubview:lab];
    
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == _tableViewHis) {
        return 40.0;
    }
    return 0.0;
}
//
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableViewHis) {
        NSString *str = datas[indexPath.row];
        [self loadData:str];
    }else{
        NSDictionary *dic = array[indexPath.row];
        KSDetViewController *det = [[KSDetViewController alloc] init];
        det.name = [dic objectForKey:@"name"];
        det.det = [dic objectForKey:@"profile"];
        det.place = [dic objectForKey:@"suite"];
        det.star = [dic objectForKey:@"star"];
        det.order = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"order"] integerValue]];
        det.meid = [dic objectForKey:@"id"];
        
        NSString *pic = [dic objectForKey:@"figurepic"];
        NSArray *arr = [pic componentsSeparatedByString:@"|"];
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],arr[0]];
        det.imgUrl = imgUrl;
        [self.navigationController pushViewController:det animated:YES];
    }
}

//开锁
- (void)loadData:(NSString *)str{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_lng forKey:@"longitude"];
    [parmas setObject:_lat forKey:@"latitude"];
    [parmas setObject:@"1" forKey:@"p"];
    [parmas setObject:str forKey:@"name"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Unlocking/index",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"开锁res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            array = [responseObject objectForKey:@"result"];
            _tableView.hidden = NO;
            _tableViewHis.hidden = YES;
            NoView.hidden = YES;
            [_tableView reloadData];
        }else{
            _tableView.hidden = YES;
            _tableViewHis.hidden = YES;
            NoView.hidden = NO;
        }
        
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
